package com.emm.yixun.customer.service.impl;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.jws.WebService;

import com.emm.yixun.common.model.enums.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.emm.yixun.basic.service.AreaService;
import com.emm.yixun.basic.service.BaseCodeTypeService;
import com.emm.yixun.basic.service.BaseCodeValueService;
import com.emm.yixun.basic.service.CustomerService;
import com.emm.yixun.basic.service.DictionaryService;
import com.emm.yixun.basic.service.ProjectService;
import com.emm.yixun.common.model.Area;
import com.emm.yixun.common.model.BaseCodeType;
import com.emm.yixun.common.model.BaseCodeValue;
import com.emm.yixun.common.model.Customer;
import com.emm.yixun.common.model.Dictionary;
import com.emm.yixun.common.model.Project;
import com.emm.yixun.common.model.dto.AreaDto;
import com.emm.yixun.common.model.dto.BaseCodeTypeDto;
import com.emm.yixun.common.model.dto.BaseCodeValueDto;
import com.emm.yixun.common.model.dto.CustomerDto;
import com.emm.yixun.common.model.dto.CustomerModel;
import com.emm.yixun.common.model.dto.DictionaryDto;
import com.emm.yixun.common.model.dto.FamilyMemberModel;
import com.emm.yixun.common.response.Response;
import com.emm.yixun.common.utils.MobileUtil;
import com.emm.yixun.customer.service.CustomerExcelServiceFacade;

@Service("customerExcelServiceFacade")
@WebService(name = "com.emm.yixun.customer.service.CustomerExcelServiceFacade")
public class CustomerExcelServiceFacadeImpl implements CustomerExcelServiceFacade {

	@Autowired
	private ProjectService projectService;

	@Autowired
	private AreaService areaServiceFacade;

	@Autowired
	private DictionaryService dictionaryService;

	@Autowired
	private CustomerService customerService;

	@Autowired
	private BaseCodeValueService baseCodeValueService;

	@Autowired
	private BaseCodeTypeService baseCodeTypeService;

	private Long getId(Long merchantId, BaseCodeTypeEnum bcte, String value) {
		try {
			BaseCodeTypeDto bctd = new BaseCodeTypeDto();
			bctd.setMerchantId(merchantId);
			bctd.setCodeType("01");
			bctd.setTypeName(bcte.getDes());
			List<BaseCodeType> list = baseCodeTypeService.selectListByDto(bctd);
			if (null == list || list.size() == 0)
				return null;
			BaseCodeType bct = list.get(0);
			BaseCodeValueDto bcvd = new BaseCodeValueDto();
			bcvd.setTypeId(bct.getId());
			bcvd.setCodeName(value);
			bcvd.setMerchantId(merchantId);
			List<BaseCodeValue> bcvList = baseCodeValueService.selectListByDto(bcvd);
			if (null == bcvList || bcvList.size() == 0)
				return null;
			return bcvList.get(0).getId();
		} catch (Exception e) {
			return null;
		}
	}

	private Long getId(Map<Long, String> bcvMap, String key) {
		for (Map.Entry<Long, String> entry : bcvMap.entrySet()) {
			String value = entry.getValue();
			if (key.equals(value)) {
				return entry.getKey();
			}
		}
		return null;
	}

	public Response<CustomerDto> validateCustomerModel(CustomerModel customerModel) {
		Response<CustomerDto> response = new Response<CustomerDto>();
		StringBuffer error = new StringBuffer("");
		CustomerDto customerDto = new CustomerDto();
		try {
			String customerName = customerModel.getCustomerName();
			if (StringUtils.isNotBlank(customerName)) {
				// 添加判断客户姓名长度为5的限制
				if (customerName.length() > 20 || customerName.length() == 0) {
					error.append("客户名称不能超过5个字;");
				} else {
					customerDto.setCustomerName(customerModel.getCustomerName());
				}
			} else {
				error.append("客户名称不能为空;");
			}

			// 通过项目名称查询项目
			Project project = projectService.selectById(customerModel.getProjectId());
			if (null == project) {
				error.append("项目不存在;");
				response.fail("0000", error.toString());
				return response;
			}

			BaseCodeValueDto bcvDto = new BaseCodeValueDto();
			bcvDto.setMerchantId(project.getMerchantId());
			bcvDto.setProjectId(customerModel.getProjectId());
			List<BaseCodeValue> bcvList = baseCodeValueService.selectListFilterDelFlag(bcvDto);
			if(bcvList == null || bcvList.size() == 0) {
				error.append("该项目未设置业务参数;");
				response.fail("0000", error.toString());
				return response;
			}
			Map<Long, String> bcvMap = new HashMap<Long, String>();
			for (BaseCodeValue bcv : bcvList) {
				bcvMap.put(bcv.getId(), bcv.getCodeName());
			}

			// 移动：134、135、136、137、138、139、150、151、157(TD)、158、159、187、188
			// 联通：130、131、132、152、155、156、185、186
			// 电信：133、153、180、189、（1349卫通）
			// Pattern pattern =
			// Pattern.compile("^((13[0-9])|(15[^4,\\D])|(18[0,5-9]))\\d{8}$");
			// 验证客户联系手机号码是否重复
			String customerPhone = customerModel.getCustomerPhone();
			// 兼容数字类型(ym)
			if (StringUtils.isNotEmpty(customerPhone)) {
				if (customerPhone.indexOf(".") > 0) {
					customerPhone = customerPhone.split("\\.")[0];
				}
			} else {
				customerPhone = "";
				error.append("联系电话不能为空;");
			}
			// Matcher matcher = pattern.matcher(customerPhone);
			// boolean isMobile = matcher.matches();
			// 验证手机号格式
			Map<String, String> verifyMap = MobileUtil.verifying(customerPhone);
			if ("1".equals(verifyMap.get("flag"))) {
				CustomerDto cusDto = new CustomerDto();
				cusDto.setCustomerPhone(customerPhone);
				cusDto.setMerchantId(project.getMerchantId());
				cusDto.setProjectId(project.getId());
				List<Customer> cusEntity = customerService.selectListByDto(cusDto);
				if (cusEntity.size() > 0) {
					error.append("联系电话与项目内联系电话重复("+customerPhone+");");
				}
				cusDto = new CustomerDto();
				cusDto.setPeMobile(customerPhone);
				cusDto.setMerchantId(project.getMerchantId());
				cusDto.setProjectId(project.getId());
				cusEntity = customerService.selectListByDto(cusDto);
				if (cusEntity.size() > 0) {
					error.append("联系电话与项目内手机号码重复("+customerPhone+");");
				}
				customerDto.setCustomerPhone(customerPhone);// 电话
			} else {
				error.append("客户联系电话格式错误("+customerPhone+");");
			}
			/*
			 * JHSong_2017-02-07_添加手机号码格式验证
			 * if(customerModel.getCustomerPhone()!=null&&!customerModel.getCustomerPhone().
			 * equals("")){ //验证客户联系手机号码是否重复 String
			 * customerPhone=customerModel.getCustomerPhone(); //兼容数字类型(ym)
			 * if(customerPhone.indexOf(".")>0){
			 * customerPhone=customerPhone.split("\\.")[0]; } CustomerDto cusDto = new
			 * CustomerDto(); cusDto.setCustomerPhone(customerPhone);
			 * cusDto.setMerchantId(project.getMerchantId());
			 * cusDto.setProjectId(project.getId()); List<Customer> cusEntity =
			 * customerService.selectListByDto(cusDto); if(cusEntity.size() > 0){
			 * error.append("客户联系电话重复;"); }else{
			 * customerDto.setCustomerPhone(customerPhone);//电话 } }else{
			 * error.append("客户联系电话不能为空;"); }
			 */
			// 验证意向等级
			String levelName = customerModel.getLevelName();
			if (StringUtils.isNotBlank(levelName)) {
				IntentionLevelEnum intentionLevelEnum = IntentionLevelEnum.getByDescription(levelName);
				if (null == intentionLevelEnum) {
					error.append("意向等级错误;");
				}
				customerDto.setIntentionLevel(intentionLevelEnum.getNo());// 意向等级
			}else {
				error.append("意向等级不能为空;");
			}

			// 验证性别
			String sexName = customerModel.getSexName();
			if (StringUtils.isNotBlank(sexName)) {
				CustomerSexEnum customerSexEnum = CustomerSexEnum.getByDescription(sexName);
				if (null == customerSexEnum) {
					error.append("客户性别错误;");
				}
				customerDto.setCustomerSex(customerSexEnum.getNo());// 性别
			}

			// 验证客户状态
			String customerStatus = customerModel.getCustomerStatus();
			// 20160905需求变更注释
			if (StringUtils.isNotBlank(customerStatus)) {
				CustomerStatusEnum customerStatusEnum = CustomerStatusEnum.getByDescription(customerStatus);
				if (null == customerStatusEnum) {
					error.append("客户状态错误;");
				} else {
					customerDto.setCustomerStatus(customerStatusEnum.getNo());// 客户状态
				}

			}

			// 客户性质
			String customerXingzhi = customerModel.getCustomerXingzhi();
			// 20160905需求变更注释
			if (StringUtils.isNotBlank(customerXingzhi)) {
				boolean existsFlag = false;
				Long key = null;
				String value = null;
				for (Map.Entry<Long, String> entry : bcvMap.entrySet()) {
					value = entry.getValue();
					if (customerXingzhi.equals(value)) {
						existsFlag = true;
						key = entry.getKey();
						value = entry.getValue();
						break;
					}
				}
				if (existsFlag) {
					customerDto.setCustomerOrigin(String.valueOf(key));
				} else {
					error.append("客户性质错误;");
				}
			}

			// 获知途径
			String huozhi = customerModel.getHuozhi();
			// 20160905需求变更注释
			if ((huozhi != null && !huozhi.equals(""))) {
				boolean existsFlag = false;
				Long key = null;
				String value = null;
				for (Map.Entry<Long, String> entry : bcvMap.entrySet()) {
					value = entry.getValue();
					if (huozhi.equals(value)) {
						existsFlag = true;
						key = entry.getKey();
						value = entry.getValue();
						break;
					}
				}
				if (existsFlag) {
					customerDto.setInformedWay(String.valueOf(key));
				} else {
					error.append("获知途径错误;");
				}
			}

			// 置业动机
			String zhiye = customerModel.getZhiye();
			// 20160905需求变更注释
			if ((zhiye != null && !zhiye.equals(""))) {
				boolean existsFlag = false;
				Long key = null;
				String value = null;
				for (Map.Entry<Long, String> entry : bcvMap.entrySet()) {
					value = entry.getValue();
					if (zhiye.equals(value)) {
						existsFlag = true;
						key = entry.getKey();
						value = entry.getValue();
						break;
					}
				}
				if (existsFlag) {
					customerDto.setRqTheirMotives(String.valueOf(key));
				} else {
					error.append("置业动机错误;");
				}
			}

			// 关注重点
			String guanzhu = customerModel.getGuanzhu();
			if (StringUtils.isNotBlank(guanzhu)) {
				Long id = getId(bcvMap, guanzhu);
				if (null == id) {
					error.append("关注重点错误;");
				} else {
					customerDto.setRqFocusId(String.valueOf(id));
				}

			}

			// 需求楼层
			String xuqiulouceng = customerModel.getXuqiulouceng();
			if (xuqiulouceng != null && !xuqiulouceng.equals("")) {
				boolean existsFlag = false;
				Long key = null;
				String value = null;
				for (Map.Entry<Long, String> entry : bcvMap.entrySet()) {
					value = entry.getValue();
					if (xuqiulouceng.equals(value)) {
						existsFlag = true;
						key = entry.getKey();
						value = entry.getValue();
						break;
					}
				}
				if (existsFlag) {
					customerDto.setRqDemandFloor(String.valueOf(key));
				} else {
					error.append("需求楼层错误;");
				}
			}

			// 需求户型规格
			String xuqiuhuxingguige = customerModel.getXuqiuhuxingguige();
			if (xuqiuhuxingguige != null && !xuqiuhuxingguige.equals("")) {
				XuQiuHuXingEnum xuQiuHuXingEnum = XuQiuHuXingEnum.getByDescription(xuqiuhuxingguige);
				if (null == xuQiuHuXingEnum) {
					error.append("需求户型规格错误;");
				} else {
					customerDto.setXuqiuhuxingType(xuQiuHuXingEnum.getNo());// 需求户型规格
				}

			}

			// 购买车位
			String goumaichewei = customerModel.getGoumaichewei();
			if (goumaichewei != null && !goumaichewei.equals("")) {
				BuyCarEnum buyCarEnum = BuyCarEnum.getByDescription(goumaichewei);
				if (null == buyCarEnum) {
					error.append("购买车位错误;");
				} else {
					customerDto.setBuyCar(buyCarEnum.getNo());// 购买车位
				}

			}

			// 希望提供的生活服务
			String xiwangshenghuo = customerModel.getXiwangshenghuo();
			if (StringUtils.isNotBlank(xiwangshenghuo)) {
				Long id = getId(project.getMerchantId(), BaseCodeTypeEnum.TYPE_SIX, xiwangshenghuo);
				if (null == id) {
					error.append("生活服务错误;");
				} else {
					customerDto.setRqServicesId(id.toString());
				}

			}

			// 生活配套
			String shenghuopeitao = customerModel.getShenghuopeitao();
			if (StringUtils.isNotBlank(shenghuopeitao)) {
				Long id = getId(project.getMerchantId(), BaseCodeTypeEnum.TYPE_SEVEN, shenghuopeitao);
				if (null == id) {
					error.append("生活配套错误;");
				} else {
					customerDto.setRqLifeSupport(String.valueOf(id));
				}
			}

			// 付款方式
			String fukuanfangshi = customerModel.getFukuanfangshi();
			if (fukuanfangshi != null && !fukuanfangshi.equals("")) {
				PaymentMethodEnum rqPaymentMethodEnum = PaymentMethodEnum.getByDescription(fukuanfangshi);
				if (null == rqPaymentMethodEnum) {
					error.append("付款方式错误;");
				} else {
					customerDto.setRqPaymentMethod(rqPaymentMethodEnum.getNo());
				}

			}

			// 家庭结构
			String jiatingjiegou = customerModel.getJiatingjiegou();
			if (jiatingjiegou != null && !jiatingjiegou.equals("")) {
				boolean existsFlag = false;
				Long key = null;
				String value = null;
				for (Map.Entry<Long, String> entry : bcvMap.entrySet()) {
					value = entry.getValue();
					if (jiatingjiegou.equals(value)) {
						existsFlag = true;
						key = entry.getKey();
						value = entry.getValue();
						break;
					}
				}
				if (existsFlag) {
					customerDto.setFamilyJie(String.valueOf(key));
				} else {
					error.append("家庭结构错误;");
				}
			}

			// 希望庭院具备功能
			String xiwangtingyuan = customerModel.getXiwangtingyuan();
			if (xiwangtingyuan != null && !xiwangtingyuan.equals("")) {
				boolean existsFlag = false;
				Long key = null;
				String value = null;
				for (Map.Entry<Long, String> entry : bcvMap.entrySet()) {
					value = entry.getValue();
					if (xiwangtingyuan.equals(value)) {
						existsFlag = true;
						key = entry.getKey();
						value = entry.getValue();
						break;
					}
				}
				if (existsFlag) {
					customerDto.setRqCourtyardFunction(String.valueOf(key));
				} else {
					error.append("希望庭院具备功能错误;");
				}

			}

			// 庭院需求面积
			if (customerModel.getTingyuanxuqiu() != null && !customerModel.getTingyuanxuqiu().equals("")) {
				customerDto.setRqCourtyardArea(new BigDecimal(customerModel.getTingyuanxuqiu()));
			}

			// 首次接触方式
			String jiechufangshi = customerModel.getJiechufangshi();
			// 20160905需求变更注释
			if ((jiechufangshi != null && !jiechufangshi.equals(""))) {
				boolean existsFlag = false;
				Long key = null;
				String value = null;
				for (Map.Entry<Long, String> entry : bcvMap.entrySet()) {
					value = entry.getValue();
					if (jiechufangshi.equals(value)) {
						existsFlag = true;
						key = entry.getKey();
						value = entry.getValue();
						break;
					}
				}
				if (existsFlag) {
					//20180625需求，拆分来电/来访
					if(MerchantEnum.GREEN_TOWN.getNo().equals(String.valueOf(project.getMerchantId()))){
						if("来电".equals(jiechufangshi)) {
							customerDto.setFtContactWay(String.valueOf(key));
						}else {
							customerDto.setFtContactWay1(String.valueOf(key));
						}
					}else{
						customerDto.setFtContactWay(String.valueOf(key));
					}
				} else {
					error.append("首次接触方式错误;");
				}
			}

			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			// 首次接触时间
			if (StringUtils.isNotEmpty(customerModel.getJiechushijian())) {
				String jiechushijian = customerModel.getJiechushijian();
				// 目前是2017年,距离3000年还很早,就以二为标准...
				// 此处处理的是纯中文时间,例如: 二○一七年一月一日
				if (jiechushijian.indexOf("二") == 0) {
					jiechushijian = changeToNumber(jiechushijian);
				}
				sdf = new SimpleDateFormat(getFormatString(jiechushijian));
				// 20160905需求变更注释
				if (jiechushijian != null && !jiechushijian.equals("")) {
					try {
						//20180625需求，拆分来电/来访
						if(MerchantEnum.GREEN_TOWN.getNo().equals(String.valueOf(project.getMerchantId()))){
							if("来电".equals(jiechufangshi)) {
								customerDto.setFtContactTime(sdf.parse(jiechushijian));
							}else {
								customerDto.setFtContactTime1(sdf.parse(jiechushijian));
							}
						}else{
							customerDto.setFtContactTime(sdf.parse(jiechushijian));
						}
					} catch (ParseException e) {
						error.append("首次接触时间错误;");
					}
				}
			}

			// 首次接触内容
			// 20160905需求变更注释
			if ((customerModel.getGoutongneirong() != null && !customerModel.getGoutongneirong().equals(""))) {
				//20180625需求，拆分来电/来访
				if(MerchantEnum.GREEN_TOWN.getNo().equals(String.valueOf(project.getMerchantId()))){
					if("来电".equals(jiechufangshi)) {
						customerDto.setFtContactContent(customerModel.getGoutongneirong());
					}else {
						customerDto.setFtContactContent1(customerModel.getGoutongneirong());
					}
				}else{
					customerDto.setFtContactContent(customerModel.getGoutongneirong());
				}

			}

			// 下次跟进时间
			if (StringUtils.isNotEmpty(customerModel.getXiacigenjingshijian())) {
				String xiacigenjingshijian = customerModel.getXiacigenjingshijian();
				if (xiacigenjingshijian.indexOf("二") == 0) {
					xiacigenjingshijian = changeToNumber(xiacigenjingshijian);
				}
				sdf = new SimpleDateFormat(getFormatString(xiacigenjingshijian));
				if (xiacigenjingshijian != null && !xiacigenjingshijian.equals("")) {
					try {
						customerDto.setLastFollowTime(sdf.parse(xiacigenjingshijian));
					} catch (ParseException e) {
						error.append("下次跟进时间错误;");
					}
				}
			}

			// 证件类型
			String zhengjianleixing = customerModel.getZhengjianleixing();
			if (zhengjianleixing != null && !zhengjianleixing.equals("")) {
				boolean existsFlag = false;
				Long key = null;
				String value = null;
				for (Map.Entry<Long, String> entry : bcvMap.entrySet()) {
					value = entry.getValue();
					if (zhengjianleixing.equals(value)) {
						existsFlag = true;
						key = entry.getKey();
						value = entry.getValue();
						break;
					}
				}
				if (existsFlag) {
					customerDto.setPeDocumentType(String.valueOf(key));
				} else {
					error.append("证件类型匹配错误;");
				}
			}

			// 证件号码
			customerDto.setPeDocumentNumber(customerModel.getZhengjianhaoma());

			// 联系地址
			customerDto.setPeContactAddress(customerModel.getLianxidizhi());

			// 邮编
			customerDto.setPePostcode(customerModel.getYoubian());

			// 出生日期
			if (StringUtils.isNotEmpty(customerModel.getChushengriqi())) {
				String chushengriqi = customerModel.getChushengriqi();
				if (chushengriqi.indexOf("二") == 0) {
					chushengriqi = changeToNumber(chushengriqi);
				}
				sdf = new SimpleDateFormat(getFormatString(chushengriqi));
				Date chushengriqiDate = sdf.parse(chushengriqi);
				customerDto.setPeBirth(sdf.format(chushengriqiDate));
			}

			// 年龄
			// 20160905需求变更注释
			String age = customerModel.getAge();
			if (StringUtils.isNotBlank(age)) {
				if (age.indexOf(".") > 0) {
					customerDto.setPeAge(customerModel.getAge().substring(0, customerModel.getAge().indexOf(".")));
				} else {
					customerDto.setPeAge(age);
				}

			}

			// 学历
			String xueli = customerModel.getXueli();
			if (StringUtils.isNotBlank(xueli)) {
				Long id = getId(bcvMap, xueli);
				if (null == id) {
					error.append("学历错误;");
				} else {
					customerDto.setPeAcademicQualifications(String.valueOf(id));
				}
			}

			// 户籍所在地
			String hujisuozaidi = customerModel.getHujisuozaidi();
			if (hujisuozaidi != null && !hujisuozaidi.equals("")) {
				HujiEnum hujiEnum = HujiEnum.getByDescription(hujisuozaidi);
				if (null == hujiEnum) {
					error.append("户籍所在地错误;");
				} else {
					customerDto.setPeDomicilePlace(hujiEnum.getNo());
				}

			}

			/**
			 * 我的部分
			 */
			// 验证从事行业
			String congshihangye = customerModel.getCongshihangye();
			if (StringUtils.isNotBlank(congshihangye)) {
				Long id = getId(bcvMap, congshihangye);
				if (null == id) {
					error.append("从事行业错误;");
				} else {
					customerDto.setCongshihangye(String.valueOf(id));
				}
			}
			// 验证公司性质
			String gongsixingzhi = customerModel.getGongsixingzhi();
			if (StringUtils.isNotBlank(gongsixingzhi)) {
				Long id = getId(bcvMap, gongsixingzhi);
				if (null == id) {
					error.append("公司性质错误;");
				} else {
					customerDto.setCompanyXingzhi(String.valueOf(id));
				}
			}
			// 公司营业额
			String gongsinianyingye = customerModel.getGongsinianyingye();
			customerDto.setCompanyYingye(gongsinianyingye);
			// 固定号码
			String gudinghaoma = customerModel.getGudinghaoma();
			customerDto.setPeTelephone(gudinghaoma);
			// 手机号码
			if (StringUtils.isNotEmpty(customerModel.getPhone())) {
				String phone = customerModel.getPhone();
				Map<String, String> verifyMap1 = MobileUtil.verifying(phone);
				if ("1".equals(verifyMap1.get("flag"))) {
					CustomerDto cusDto = new CustomerDto();
					cusDto.setCustomerPhone(phone);
					cusDto.setMerchantId(project.getMerchantId());
					cusDto.setProjectId(project.getId());
					List<Customer> cusEntity = customerService.selectListByDto(cusDto);
					if (cusEntity.size() > 0) {
						error.append("手机号码与项目内联系电话重复;");
					}
					cusDto = new CustomerDto();
					cusDto.setPeMobile(phone);
					cusDto.setMerchantId(project.getMerchantId());
					cusDto.setProjectId(project.getId());
					cusEntity = customerService.selectListByDto(cusDto);
					if (cusEntity.size() > 0) {
						error.append("手机号码与项目内手机号码重复;");
					}
					customerDto.setPeMobile(phone);
				} else {
					error.append("手机号码格式错误;");
				}
			}

			// 手机号码2
			// 邮编
			String email = customerModel.getEmail();
			customerDto.setPeEmail(email);
			// qq
			String qq = customerModel.getQq();
			customerDto.setQqNumber(qq);
			// 微信
			String weixin = customerModel.getWeixin();
			customerDto.setPeWechat(weixin);
			// 验证是否员工
			String isyuangong = customerModel.getIsyuangong();
			if (isyuangong != null && !isyuangong.equals("")) {
				IsAvlidEnum isAvlidEnum = IsAvlidEnum.getByDescription(isyuangong);
				if (null == isAvlidEnum) {
					error.append("是否员工错误;");
				} else {
					customerDto.setIsYuangong(isAvlidEnum.getNo());
				}

			}
			// 验证是否本公司业主
			String isgongsiyezhu = customerModel.getIsgongsiyezhu();
			if (isgongsiyezhu != null && !isgongsiyezhu.equals("")) {
				IsOwnerCompanyEnum isOwnerCompanyEnum = IsOwnerCompanyEnum.getByDescription(isgongsiyezhu);
				if (null == isOwnerCompanyEnum) {
					error.append("是否本公司业主错误;");
				} else {
					customerDto.setIsYezhu(isOwnerCompanyEnum.getNo());
				}

			}
			// 验证居住省
			String juzhusheng = customerModel.getJuzhusheng();
			AreaDto areaDto = new AreaDto();
			areaDto.setAreaName(juzhusheng);
			areaDto.setOrders(" t.id desc ");
			List<Area> area = null;
			// 20160905需求变更注释
			if ((juzhusheng != null && !juzhusheng.equals(""))) {
				try {
					area = areaServiceFacade.selectListByDto(areaDto);
					areaDto.setOrders(null);
				} catch (Exception e) {
					error.append("居住省错误;");
				}
				if (area == null) {
					error.append("居住省错误;");
				} else {
					customerDto.setPeResidenceProvinceId(area.get(0).getId());
				}

			}
			// 验证居住市
			String juzhushi = customerModel.getJuzhushi();
			areaDto = new AreaDto();
			areaDto.setAreaName(juzhushi);
			areaDto.setOrders(" t.id asc ");
			List<Area> area2 = null;
			// 20160905需求变更注释
			if ((juzhushi != null && !juzhushi.equals(""))) {
				try {
					area2 = areaServiceFacade.selectListByDto(areaDto);
					areaDto.setOrders(null);
				} catch (Exception e) {
					error.append("居住市错误;");
				}
				if (area2 == null) {
					error.append("居住市错误;");
				} else {
					customerDto.setPeResidenceCityId(area2.get(0).getId());
				}

			}
			// 验证居住区
			String juzhuqu = customerModel.getJuzhuqu();
			areaDto = new AreaDto();
			areaDto.setAreaName(juzhuqu);
			List<Area> area3 = null;
			// 20160905需求变更注释
			if ((juzhuqu != null && !juzhuqu.equals(""))) {
				try {
					area3 = areaServiceFacade.selectListByDto(areaDto);
				} catch (Exception e) {
					// error.append("居住区错误;");
				}
				if (area3 == null) {
					error.append("居住区错误;");
				} else {
					customerDto.setPeResidenceAreaId(area3.get(0).getId());
				}

			}
			// 小区
			String xiaoqu = customerModel.getXiaoqu();
			customerDto.setPePlot(xiaoqu);
			// 居住详细地址
			String juzhuxiangxidizhi = customerModel.getJuzhuxiangxidizhi();
			customerDto.setPeDetailedAddress(juzhuxiangxidizhi);
			// 验证目前居住面积
			String muqianmianji = customerModel.getMuqianmianji();
			if (muqianmianji != null && !muqianmianji.equals("")) {
				ReCurrentlyAreaEnum reCurrentlyAreaEnum = ReCurrentlyAreaEnum.getByDescription(muqianmianji);
				if (null == reCurrentlyAreaEnum) {
					error.append("目前居住面积错误;");
				} else {
					customerDto.setReCurrentlyArea(reCurrentlyAreaEnum.getNo());
				}

			}
			// 验证是否与老人同住
			String isoldman = customerModel.getIsoldman();
			if (isoldman != null && !isoldman.equals("")) {
				IsAvlidEnum isAvlidEnum3 = IsAvlidEnum.getByDescription(isoldman);
				if (null == isAvlidEnum3) {
					error.append("是否与老人同住错误;");
				} else {
					customerDto.setIsLaoren(isAvlidEnum3.getNo());
				}

			}
			// 验证是否有子女
			String iszinv = customerModel.getIszinv();
			if (iszinv != null && !iszinv.equals("")) {
				IsAvlidEnum isAvlidEnum4 = IsAvlidEnum.getByDescription(iszinv);
				if (null == isAvlidEnum4) {
					error.append("是否与老人同住错误;");
				} else {
					customerDto.setIsZinv(isAvlidEnum4.getNo());
				}

			}
			// 验证家庭年收入
			String jiatingnianshouru = customerModel.getJiatingnianshouru();
			if (jiatingnianshouru != null && !jiatingnianshouru.equals("")) {
				PeHouseholdIncomeEnum peHouseholdIncomeEnum = PeHouseholdIncomeEnum.getByDescription(jiatingnianshouru);
				if (null == peHouseholdIncomeEnum) {
					error.append("家庭年收入错误;");
				} else {
					customerDto.setPeHouseholdIncome(peHouseholdIncomeEnum.getNo());
				}

			}
			// 验证工作省
			String gongzuosheng = customerModel.getGongzuosheng();
			areaDto = new AreaDto();
			areaDto.setAreaName(gongzuosheng);
			areaDto.setOrders(" t.id desc ");
			List<Area> area4 = null;
			// 20160905需求变更注释
			if ((gongzuosheng != null && !gongzuosheng.equals(""))) {
				try {
					area4 = areaServiceFacade.selectListByDto(areaDto);
					areaDto.setOrders(null);
				} catch (Exception e) {
					error.append("工作省错误;");
				}
				if (area4 == null) {
					error.append("工作省错误;");
				} else {
					customerDto.setPeWorkaroundProvinceId(area4.get(0).getId());
				}

			}
			// 验证工作市
			String gongzuoshi = customerModel.getGongzuoshi();
			areaDto = new AreaDto();
			areaDto.setAreaName(gongzuoshi);
			areaDto.setOrders(" t.id asc ");
			List<Area> area5 = null;
			// 20160905需求变更注释
			if ((gongzuoshi != null && !gongzuoshi.equals(""))) {
				try {
					area5 = areaServiceFacade.selectListByDto(areaDto);
					areaDto.setOrders(null);
				} catch (Exception e) {
					// error.append("工作市错误;");
				}
				if (area5 == null) {
					error.append("工作市错误;");
				} else {
					customerDto.setPeWorkaroundCityId(area5.get(0).getId());
				}

			}
			// 验证工作区
			String gongzuoqu = customerModel.getGongzuoqu();
			areaDto = new AreaDto();
			areaDto.setAreaName(gongzuoqu);
			List<Area> area6 = null;
			// 20160905需求变更注释
			if ((gongzuoqu != null && !gongzuoqu.equals(""))) {
				try {
					area6 = areaServiceFacade.selectListByDto(areaDto);
				} catch (Exception e) {
					// error.append("工作区错误;");
				}
				if (area6 == null) {
					error.append("工作区错误;");
				} else {
					customerDto.setPeWorkaroundAreaId(area6.get(0).getId());
				}

			}
			// 工作详情地址
			String gongzuoxiangxidizhi = customerModel.getGongzuoxiangxidizhi();
			customerDto.setPeWorkaroundAddress(gongzuoxiangxidizhi);
			// 验证兴趣爱好
			String xingquaihao = customerModel.getXingquaihao();
			if (xingquaihao != null && !xingquaihao.equals("")) {
				boolean existsFlag = false;
				Long key = null;
				String value = null;
				for (Map.Entry<Long, String> entry : bcvMap.entrySet()) {
					value = entry.getValue();
					if (xingquaihao.equals(value)) {
						existsFlag = true;
						key = entry.getKey();
						value = entry.getValue();
						break;
					}
				}
				if (existsFlag) {
					customerDto.setPeHobbyId(key.toString());
				} else {
					error.append("兴趣爱好匹配错误;");
				}
			}
			// 验证车架品牌
			String chejiapinpai = customerModel.getChejiapinpai();
			if (chejiapinpai != null && !chejiapinpai.equals("")) {
				boolean existsFlag = false;
				Long key = null;
				String value = null;
				for (Map.Entry<Long, String> entry : bcvMap.entrySet()) {
					value = entry.getValue();
					if (chejiapinpai.equals(value)) {
						existsFlag = true;
						key = entry.getKey();
						value = entry.getValue();
						break;
					}
				}
				if (existsFlag) {
					customerDto.setPeFrameBrandId(key);
				} else {
					error.append("车架品牌错误;");
				}
			}
			// 验证乐于参加的活动类型
			String leyuhuodong = customerModel.getLeyuhuodong();
			if (leyuhuodong != null && !leyuhuodong.equals("")) {
				boolean existsFlag = false;
				Long key = null;
				String value = null;
				for (Map.Entry<Long, String> entry : bcvMap.entrySet()) {
					value = entry.getValue();
					if (leyuhuodong.equals(value)) {
						existsFlag = true;
						key = entry.getKey();
						value = entry.getValue();
						break;
					}
				}
				if (existsFlag) {
					customerDto.setPeActivityType(String.valueOf(key));
				} else {
					error.append("乐于参加的活动类型错误;");
				}
			}
			// 验证日常信息获取途径
			String richangxinxi = customerModel.getRichangxinxi();
			if (richangxinxi != null && !richangxinxi.equals("")) {
				boolean existsFlag = false;
				Long key = null;
				String value = null;
				for (Map.Entry<Long, String> entry : bcvMap.entrySet()) {
					value = entry.getValue();
					if (richangxinxi.equals(value)) {
						existsFlag = true;
						key = entry.getKey();
						value = entry.getValue();
						break;
					}
				}
				if (existsFlag) {
					customerDto.setRichangxinxi(String.valueOf(key));
				} else {
					error.append("日常信息获取途径错误;");
				}
			}
			// 本地购房次数
			String bendigoufang = customerModel.getBendigoufang();
			if (bendigoufang != null && !bendigoufang.equals("")) {
				customerDto.setReLocalPurchase(Long.valueOf(bendigoufang));
			}
			// 目前家庭住宅已按揭数
			String muqianyianjie = customerModel.getMuqianyianjie();
			if (muqianyianjie != null && !muqianyianjie.equals("")) {
				customerDto.setReResidentialMortgage(Long.valueOf(muqianyianjie));
			}
			// 目前家庭持有房数
			String muqianfangshu = customerModel.getMuqianfangshu();
			if (muqianfangshu != null && !muqianfangshu.equals("")) {
				customerDto.setReCurrentHoldings(Long.valueOf(muqianfangshu));
			}
			// 目前居住的物业类型
			String muqianwuye = customerModel.getMuqianwuye();
			if (muqianwuye != null && !muqianwuye.equals("")) {
				boolean existsFlag = false;
				Long key = null;
				String value = null;
				for (Map.Entry<Long, String> entry : bcvMap.entrySet()) {
					value = entry.getValue();
					if (muqianwuye.equals(value)) {
						existsFlag = true;
						key = entry.getKey();
						value = entry.getValue();
						break;
					}
				}
				if (existsFlag) {
					customerDto.setReCurrentlyProperty(String.valueOf(key));
				} else {
					error.append("目前居住的物业类型错误;");
				}
			}
			// 目前居住的户型结构
			String muqianhuxingjiegou = customerModel.getMuqianhuxingjiegou();
			if (muqianhuxingjiegou != null && !muqianhuxingjiegou.equals("")) {
				boolean existsFlag = false;
				Long key = null;
				String value = null;
				for (Map.Entry<Long, String> entry : bcvMap.entrySet()) {
					value = entry.getValue();
					if (muqianhuxingjiegou.equals(value)) {
						existsFlag = true;
						key = entry.getKey();
						value = entry.getValue();
						break;
					}
				}
				if (existsFlag) {
					customerDto.setReCurrentlyStructure(String.valueOf(key));
				} else {
					error.append("目前居住的户型结构错误;");
				}
			}
			// 目前居住/办公的房子属性
			String muqianfangzishuxing = customerModel.getMuqianfangzishuxing();
			if (StringUtils.isNotBlank(muqianfangzishuxing)) {
				Long id = getId(bcvMap, muqianfangzishuxing);
				if (null == id) {
					error.append("目前居住/办公的房子属性错误;");
				} else {
					customerDto.setReCurrentlyHouse(String.valueOf(id));
				}
			}
			// 工作日联系时间
			String workdaylianxishijian = customerModel.getWorkdaylianxishijian();
			if (workdaylianxishijian != null && !workdaylianxishijian.equals("")) {
				CoContactTimeEnum coContactTimeEnum = CoContactTimeEnum.getByDescription(workdaylianxishijian);
				if (null == coContactTimeEnum) {
					error.append("工作日联系时间错误;");
				} else {
					customerDto.setCoContactTime(coContactTimeEnum.getNo());
				}

			}
			// 工作日联系方式
			String workdaylianxifangshi = customerModel.getWorkdaylianxifangshi();
			if (StringUtils.isNotBlank(workdaylianxifangshi)) {
				Long id = getId(bcvMap, workdaylianxifangshi);
				if (null == id) {
					error.append("工作日联系方式错误;");
				} else {
					customerDto.setCoInformationDays(String.valueOf(id));
				}
			}
			// 周末联系时间
			String freedaylianxishijian = customerModel.getFreedaylianxishijian();
			if (freedaylianxishijian != null && !freedaylianxishijian.equals("")) {
				CoContactWeekendEnum coContactWeekendEnum = CoContactWeekendEnum.getByDescription(freedaylianxishijian);
				if (null == coContactWeekendEnum) {
					error.append("周末联系时间错误;");
				} else {
					customerDto.setCoContactWeekend(coContactWeekendEnum.getNo());
				}

			}
			// 周末联系方式
			String freedaylianxifangshi = customerModel.getFreedaylianxifangshi();
			if (StringUtils.isNotBlank(freedaylianxifangshi)) {
				Long id = getId(bcvMap, freedaylianxifangshi);
				if (null == id) {
					error.append("周末联系方式错误;");
				} else {
					customerDto.setCoWeekendInformation(String.valueOf(id));
				}
			}

			// 处理结婚纪念日

			// todo
			customerDto.setProjectCode(project.getProjectCode());
			customerDto.setProjectId(project.getId());
			customerDto.setAccessCode(project.getProjectCode());

			List<FamilyMemberModel> fmmList = convertFamilyMemberModel(customerModel, error, bcvMap);
			customerDto.setFamilyMemberLists(fmmList);
		} catch (Exception e) {
			e.printStackTrace();
			error.append("系统处理异常;");
		}
		if (error.toString().equals("")) {
			response.success(customerDto);
		} else {
			response.fail("0000", error.toString());
		}
		return response;
	}

	private String autoFormatDate(String dateStr) {
		if (StringUtils.isBlank(dateStr)) {
			return null;
		}
		try {
			if (dateStr.indexOf("二") == 0) {
				dateStr = changeToNumber(dateStr);
			}
			SimpleDateFormat sdf = new SimpleDateFormat(getFormatString(dateStr));
			SimpleDateFormat sdfFormat = new SimpleDateFormat("yyyy-MM-dd");
			return sdfFormat.format(sdf.parse(dateStr));
		} catch (Exception e) {
			return null;
		}
	}

	private List<FamilyMemberModel> convertFamilyMemberModel(CustomerModel customerModel, StringBuffer error,
			Map<Long, String> bcvMap) {
		List<FamilyMemberModel> list = new ArrayList<FamilyMemberModel>();
		Long merchantId = customerModel.getMerchantId();
		// 家庭成员1
		String memberName = customerModel.getFamilyValueOneOne();
		String documentType = customerModel.getFamilyValueOneTwo();
		String documentNumber = customerModel.getFamilyValueOneThree();
		String birthday = customerModel.getFamilyValueOneFour();
		String marryday = customerModel.getFamilyValueOneFive();
		FamilyMemberModel familyMemberModel = new FamilyMemberModel();
		String errorInfo = "";
		if (StringUtils.isNotBlank(memberName) || StringUtils.isNotBlank(documentType)
				|| StringUtils.isNotBlank(documentNumber) || StringUtils.isNotBlank(birthday)
				|| StringUtils.isNotBlank(marryday)) {
			familyMemberModel.setMerchantId(String.valueOf(merchantId));
			familyMemberModel.setMemberName(memberName);
			familyMemberModel.setDocumentType(documentType);
			// 证件号码
			familyMemberModel.setDocumentNumber(documentNumber);
			// 生日
			familyMemberModel.setBirthday(birthday);
			// 结婚纪念日
			familyMemberModel.setMarryday(autoFormatDate(marryday));
			errorInfo = validateFamilyModel(merchantId, familyMemberModel, bcvMap);
			if (StringUtils.isBlank(errorInfo)) {
				list.add(familyMemberModel);
			} else {
				error.append("家庭成员1" + errorInfo);
			}
		}

		// 家庭成员2
		memberName = customerModel.getFamilyValueTwoOne();
		documentType = customerModel.getFamilyValueTwoTwo();
		documentNumber = customerModel.getFamilyValueTwoThree();
		birthday = customerModel.getFamilyValueTwoFour();
		marryday = customerModel.getFamilyValueTwoFive();
		if (StringUtils.isNotBlank(memberName) || StringUtils.isNotBlank(documentType)
				|| StringUtils.isNotBlank(documentNumber) || StringUtils.isNotBlank(birthday)
				|| StringUtils.isNotBlank(marryday)) {
			familyMemberModel = new FamilyMemberModel();
			familyMemberModel.setMerchantId(String.valueOf(merchantId));
			familyMemberModel.setMemberName(memberName);
			familyMemberModel.setDocumentType(documentType);
			// 证件号码
			familyMemberModel.setDocumentNumber(documentNumber);
			// 生日
			familyMemberModel.setBirthday(birthday);
			// 结婚纪念日
			familyMemberModel.setMarryday(marryday);
			errorInfo = validateFamilyModel(merchantId, familyMemberModel, bcvMap);
			if (StringUtils.isBlank(errorInfo)) {
				list.add(familyMemberModel);
			} else {
				error.append("家庭成员2" + errorInfo);
			}
		}

		// 家庭成员3
		memberName = customerModel.getFamilyValueThreeOne();
		documentType = customerModel.getFamilyValueThreeTwo();
		documentNumber = customerModel.getFamilyValueThreeThree();
		birthday = customerModel.getFamilyValueThreeFour();
		marryday = customerModel.getFamilyValueThreeFive();
		if (StringUtils.isNotBlank(memberName) || StringUtils.isNotBlank(documentType)
				|| StringUtils.isNotBlank(documentNumber) || StringUtils.isNotBlank(birthday)
				|| StringUtils.isNotBlank(marryday)) {
			familyMemberModel = new FamilyMemberModel();

			familyMemberModel.setMerchantId(String.valueOf(merchantId));
			familyMemberModel.setMemberName(memberName);
			familyMemberModel.setDocumentType(documentType);
			// 证件号码
			familyMemberModel.setDocumentNumber(documentNumber);
			// 生日
			familyMemberModel.setBirthday(birthday);
			// 结婚纪念日
			familyMemberModel.setMarryday(marryday);
			errorInfo = validateFamilyModel(merchantId, familyMemberModel, bcvMap);
			if (StringUtils.isBlank(errorInfo)) {
				list.add(familyMemberModel);
			} else {
				error.append("家庭成员3" + errorInfo);
			}
		}

		// 家庭成员4
		memberName = customerModel.getFamilyValueFourOne();
		documentType = customerModel.getFamilyValueFourTwo();
		documentNumber = customerModel.getFamilyValueFourThree();
		birthday = customerModel.getFamilyValueFourFour();
		marryday = customerModel.getFamilyValueFourFive();
		if (StringUtils.isNotBlank(memberName) || StringUtils.isNotBlank(documentType)
				|| StringUtils.isNotBlank(documentNumber) || StringUtils.isNotBlank(birthday)
				|| StringUtils.isNotBlank(marryday)) {
			familyMemberModel = new FamilyMemberModel();
			familyMemberModel.setMerchantId(String.valueOf(merchantId));
			familyMemberModel.setMemberName(memberName);
			familyMemberModel.setDocumentType(documentType);
			// 证件号码
			familyMemberModel.setDocumentNumber(documentNumber);
			// 生日
			familyMemberModel.setBirthday(birthday);
			// 结婚纪念日
			familyMemberModel.setMarryday(marryday);
			errorInfo = validateFamilyModel(merchantId, familyMemberModel, bcvMap);
			if (StringUtils.isBlank(errorInfo)) {
				list.add(familyMemberModel);
			} else {
				error.append("家庭成员4" + errorInfo);
			}
		}

		return list;
	}

	private String validateFamilyModel(Long merchantId, FamilyMemberModel familyMemberModel, Map<Long, String> bcvMap) {
		String error = "";
		String documentType = familyMemberModel.getDocumentType();
		// 证件类型
		if (StringUtils.isNotBlank(documentType)) {
			// 用数据字典做验证
			BaseCodeValueDto bcvDto = new BaseCodeValueDto();
			bcvDto.setMerchantId(merchantId);
			bcvDto.setTypeName(BaseCodeTypeEnum.TYPE_TWELVE.getDes());
			bcvDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
			List<BaseCodeValueDto> resList = baseCodeValueService.selectListByTypeName(bcvDto);
			Boolean flag = true;
			if (resList.size() > 0) {
				for (BaseCodeValue base : resList) {
					if (base.getCodeName().equals(documentType)) {
						familyMemberModel.setDocumentType(base.getId().toString());
						break;
					} else {
						flag = false;
						// error = "证件类型错误;";
					}
				}

			}
			if (!flag) {
				error = "证件类型错误;";
			}
			/*
			 * DocumentTypeEnum documentTypeEnum =
			 * DocumentTypeEnum.getByDescription(documentType); if (null ==
			 * documentTypeEnum) { error = "证件类型错误;"; } else {
			 * familyMemberModel.setDocumentType(documentTypeEnum.getNo()); }
			 */
			/*
			 * Long documentTypeId=getId(bcvMap,documentType); if(null==documentTypeId){
			 * error="证件类型错误;"; }else{
			 * familyMemberModel.setDocumentType(String.valueOf(documentTypeId)); }
			 */
		}
		return error;
	}

	private Dictionary findDictionary(String type, String name) {
		DictionaryDto dictionaryDto = new DictionaryDto();
		dictionaryDto.setDictionaryType(type);
		dictionaryDto.setDictionaryName(name);
		Dictionary dictionary = dictionaryService.selectByDto(dictionaryDto);
		return dictionary;
	}

	public static String getEntityName(String className) {
		return className.substring(0, 1).toUpperCase() + className.substring(1, className.length());
	}

	public static String changeToNumber(String date_zh) {
		char[] dateArr = date_zh.toCharArray();
		for (int ii = 0; ii < dateArr.length; ii++) {
			switch (dateArr[ii]) {
			case '○':
				dateArr[ii] = '0';
				break;
			case '〇':
				dateArr[ii] = '0';
				break;
			case '零':
				dateArr[ii] = '0';
				break;
			case '一':
				dateArr[ii] = '1';
				break;
			case '二':
				dateArr[ii] = '2';
				break;
			case '三':
				dateArr[ii] = '3';
				break;
			case '四':
				dateArr[ii] = '4';
				break;
			case '五':
				dateArr[ii] = '5';
				break;
			case '六':
				dateArr[ii] = '6';
				break;
			case '七':
				dateArr[ii] = '7';
				break;
			case '八':
				dateArr[ii] = '8';
				break;
			case '九':
				dateArr[ii] = '9';
				break;
			default:
				break;
			}
		}
		return String.valueOf(dateArr);
	}

	public static String getFormatString(String dateStr) {
		String fmt = "yyyy-MM-dd";
		if (dateStr.indexOf("/") > 0) {
			fmt = "yyyy/MM/dd";
		} else if (dateStr.indexOf("年") > 0) {
			fmt = "yyyy年MM月dd日";
		}
		return fmt;
	}

	public static void main(String[] args) {
		String dateStr = "二零一七年一月二日";
		String fmt = "yyyy-MM-dd";
		if (dateStr.indexOf("二") >= 0) {
			dateStr = changeToNumber(dateStr);
		}
		if (dateStr.indexOf("/") > 0) {
			fmt = "yyyy/MM/dd";
		} else if (dateStr.indexOf("年") > 0) {
			fmt = "yyyy年MM月dd日";
		}
		SimpleDateFormat sdf = new SimpleDateFormat(fmt);
		try {
			System.out.println("fmt = " + fmt);
			System.out.println(sdf.parseObject(dateStr));
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

}
